function mat_c=counterlev(countmat,pos_st,flag_trend,pos_trend,pos_sh,trendmean,consvec) 
% =====================================================================
% Given an original set of counterfactual states 
% Aggregate them to obtain a level for a) selected states b) selected
% shocks 
% 
% function counterlev(mat,countmat,pos_st,pos_trend,pos_sh,trendmean,consvec);  
%
% Inputs
% ------
% COUNTMAT  countermat original [nobs nst nx] 
% POS_ST    position of the state for which to aggregate levels 
% FLAG_TREND==1 will add a trend 
% POS_TREND position of the state corresponding to the trend 
% POS_SH    position of the NX shocks for which to aggregate           
% TRENDMEAN growth rate of the trend 
% CONSVEC   vector of means to add i.e. correct for level issues 
%           (optional) 
%
% Output 
% -----
% MAT_C    [nobs length(pos_st) length(pos_sh)] 
% 
% NOTE     Order of shocks will be that of POS_SH, not of the original
%          COUNTMAT matrix 
% 
% Alejandro Justiniano  Feb 6 2009 
% ====================================================================
if nargin < 5 
    consvec=zeros(length(pos_st)); 
    if nargin < 4 
        error('Neeed for INPUTS') 
    end 
end 
mat_c=zeros( [size(countmat,1) length(pos_st) length(pos_sh)]);
% One of the SELECTED shocks at a time 
for ii=1:length(pos_sh);
    % Obtain level trend
    temptrlev=cumsum( countmat(:,pos_trend, pos_sh(ii))  +trendmean);
    for jj=1:length( pos_st );
        % Obtain the counterfactual, level adjusted of the series
        if flag_trend(jj)==1
            mat_c(:,jj,ii)= countmat(:,pos_st(jj),pos_sh(ii)) +temptrlev + consvec(jj);
        elseif flag_trend(jj)==0
            mat_c(:,jj,ii)= countmat(:,pos_st(jj),pos_sh(ii)) + consvec(jj);
        else
            error('FLAG_TREND must be 0 or 1')
        end
    end
end